package com.lxh.cp.controller;

import com.lxh.cp.utils.JsonUtils;
import com.lxh.cp.utils.WxCpUtils;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * created by lanxinghua@2dfire.com on 2020/2/23
 * 授权相关
 */
@RestController
@RequestMapping("/wx/oauth/{agentId}")
public class WxCpOauthController {
    private WxCpService wxCpService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private String oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";
    private String loginUrl = "http://chenxingxing.51vip.biz/wx/oauth/%s/login";


    /**
     * 拆分链接
     * @param agentId
     * @param url
     */
    @GetMapping("/jump")
    public void jump(@PathVariable Integer agentId,
                     String url,
                     HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        wxCpService = WxCpUtils.switchover(agentId);
        loginUrl = String.format(loginUrl, agentId);
        oauthUrl = String.format(oauthUrl, "wwd276de90ff82e1e3", loginUrl, url);
        logger.info("跳转url:" + oauthUrl);
        response.sendRedirect(oauthUrl);
    }


    /**
     * 授权链接  通过code换取用户信息
     * https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
     * 前：https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwd276de90ff82e1e3&redirect_uri=https%3a%2f%2fchenxingxing.51vip.biz%2f&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
     * 后：https://chenxingxing.51vip.biz/?code=eTrMxa-_afrQ8JsK-rnmSJdBZhCvqalYQ4ZSDZHjHP8&state=STATE
     *
     * code获取用户信息：响应结果
     * {
     *     "UserId":"ChenXingXing",
     *     "DeviceId":"d93b8209-bf41-4d15-9bd2-136138799a03",
     *     "errcode":0,
     *     "errmsg":"ok"
     * }
     */
    @GetMapping("/login")
    public void login(@PathVariable Integer agentId,
                      String code,
                      String state,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        if (StringUtils.isBlank(code)) {
            throw new IllegalArgumentException("code is empty");
        }
        wxCpService = WxCpUtils.switchover(agentId);
        try {
            WxCpOauth2UserInfo userInfo = wxCpService.getOauth2Service().getUserInfo(code);
            this.logger.info("userInfo："+ JsonUtils.toJson(userInfo));
            String userId = userInfo.getUserId();
            WxCpUser user = wxCpService.getUserService().getById(userId);
            logger.info("完整的user:" + JsonUtils.toJson(user));
            // TODO: 2020/2/24 处理用户信息 
            request.getSession().setAttribute("token", user);
            response.sendRedirect(state);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
    }


    /**
     * 创建js-sdk签名
     * @param url
     * @return
     * @throws Exception
     */
    @RequestMapping("/create/jsapi_sign")
    @ResponseBody
    public Object jssdk(@PathVariable Integer agentId,
                        @RequestParam  String url) throws Exception{
        // 切换企业微信
        wxCpService = WxCpUtils.switchover(agentId);
        logger.info("url:" + url);
        WxJsapiSignature jsapiSignature = wxCpService.createJsapiSignature(url);
        logger.info("data：" + JsonUtils.toJson(jsapiSignature));
        return jsapiSignature;
    }
}
